import { useRoutes, useLocation, useNavigate } from 'react-router-dom'
import router from './router/index'
import { useEffect } from 'react'
import { message } from 'antd'

function checkToken() {
  const token = window.localStorage.getItem('user-token')
  return token ? true : false
}

function ToHome() {
  const navigateTo = useNavigate()

  // 只在组件挂载时执行一次  
  useEffect(() => {
    navigateTo('/login')
    message.warning("您还没有登录,请登录后再访问")
  }, [])

  return <div></div>
}

function Tologin() {
  const navigateTo = useNavigate()

  // 只在组件挂载时执行一次  
  useEffect(() => {
    navigateTo('/home')
    message.warning("您已经登录过了!")
  }, [])

  return <div></div>
}

function BeforRouterEnter() {
  const oulet = useRoutes(router)
  const location = useLocation()
  const navigateTo = useNavigate()
  // 添加一个useEffect来处理token的改变  
  useEffect(() => {
    if (location.pathname === "/login" && checkToken()) {
      navigateTo('/home')
      message.warning("您已经登录过了!")
    } else if (location.pathname === "/" && !checkToken()) {
      navigateTo('/login')
      message.warning("您还没有登录,请登录后再访问")
    }
  }, [location, navigateTo]) // 依赖location和navigateTo的变化  

  if (location.pathname === "/login" && checkToken()) {
    return <Tologin />
  }

  if (location.pathname === "/" && !checkToken()) {
    return <ToHome />
  }
  return oulet
}

export default function App() {
  return (
    <div style={{ width: "100%", height: "100%" }}>
      <BeforRouterEnter />
    </div>
  )
}